<template>
	<div class="container">
		<el-form class="form" label-width="120px" label-position="top">
			<el-form-item label="请导入文件: ">
				<el-col :span="16">
					<div style="text-align: left">
						<input type="file" ref="file" />
					</div>
				</el-col>
			</el-form-item>
			<el-button type="primary" @click="plImport">确定</el-button>
		</el-form>
	</div>
</template>

<script>
import { ElMessage } from "element-plus";
import { read, utils } from "xlsx";
export default {
	name: "ImportSignUpStudent",
	data() {
		return {
			output: [],
		};
	},
	methods: {
		readExcel(e) {
			const files = e.target.files;
			// 如果没有文件名
			if (files.length <= 0) {
				return false;
			} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
				alert("上传格式不正确，请上传xls或者xlsx格式");
				return false;
			}

			const fileReader = new FileReader();
			fileReader.onload = (ev) => {
				try {
					const data = ev.target.result;
					// 切换为新的调用方式
					const workbook = read(data, {
						type: "binary",
					});
					this.output = [];
					for (let name of workbook.SheetNames) {
						this.output[name] = utils.sheet_to_json(workbook.Sheets[name]);
					}
					// console.log(this.output);
				} catch (e) {
					return false;
				}
			};
			fileReader.readAsBinaryString(files[0]);
		},
		plImport() {
			let name = "";
			let students = [];

			for (let index in this.output) {
				let item = this.output[index];
				for (let i in item[0]) {
					if (/学号/.test(item[0][i])) {
						name = i;
						break;
					}
				}

				if (/学号/.test(item[0][name])) {
					for (let j = 1; j < item.length; j++) {
						students.push(item[j][name]);
					}
				} else {
					for (let i in item) {
						let wt = item[i];
						let keys = Object.keys(wt);
						keys.forEach((key) => {
							if (/学号/.test(key)) {
								students.push(wt[key]);
							}
						});
					}
				}
			}

			// console.log(students);

			students.forEach((item) => {
				let requestBody = new URLSearchParams();
				// console.log(item);
				requestBody.append("ids", item);
				fetch(`${this.$store.getters.point}/Admin/preSignUp/setSignList`, {
					method: "POST",
					mode: "cors",
					body: requestBody,
				})
					.then((response) => response.text())
					.then((result) => {
						let data = parseInt(JSON.parse(result).code);
						if (data == 1) {
							ElMessage({
								message: "导入成功",
								type: "success",
							});
							this.$emit("success");
						} else {
							ElMessage({
								message: "报名失败",
								type: "error",
							});
						}
					});
			});
		},
	},
	mounted() {
		this.$refs.file.addEventListener("change", (e) => {
			this.readExcel(e);
		});
	},
};
</script>

<style scoped></style>
